package hook

import (
	"context"
	"encoding/json"
	"strings"
	"time"

	jmconst "gitee.com/JMArch/micro/jm-const"
	"gitee.com/JMArch/micro/metadata"
	"go.uber.org/zap"
)

var (
	EmptyRegisterHook = &Hook{
		RegisterNotice:   empty,
		UnRegisterNotice: empty,
	}

	loggerHook *zap.SugaredLogger
)

func empty(self *Hook, info interface{}) {
	return
}

type registerFormat struct {
	Time int64       `json:"time"`
	Type string      `json:"type"`
	Info interface{} `json:"info"`
}

func defaultRegisterNotice(self *Hook, info interface{}) {
	go regNoticeDo("reg", self, info)
}

func defaultUnRegisterNotice(self *Hook, info interface{}) {
	go regNoticeDo("unreg", self, info)
}
func regNoticeDo(t string, self *Hook, info interface{}) {
	data, e := json.Marshal(&registerFormat{
		Type: t,
		Time: time.Now().Unix(),
		Info: info,
	})
	if e != nil {
		loggerHook.Errorw(t, "info", info,
			"err", e)
		return
	}
	loggerHook.Debugw(t, "info", string(data))
	if self != nil && self.rpcClient != nil {
		ctx := metadata.NewContext(context.TODO(), metadata.Metadata{
			jmconst.JumeiRPCVersion:   self.cfg.RPCVersion,
			jmconst.JumeiRPCSecretKey: self.cfg.RPCSecret,
			jmconst.JumeiRPCUser:      self.cfg.SenderKey,
			jmconst.JumeiRPCPassword:  self.cfg.SecretKey,
		})
		resp, e := self.rpcClient.Send(ctx, &BCRequest{
			SenderKey:       self.cfg.SenderKey,
			SecretKey:       self.cfg.SecretKey,
			MessageClassKey: self.cfg.UnRegisterClass,
			Message:         string(data),
			Priority:        1024,
			TimeToDelay:     0,
		})
		if e != nil {
			result, err := makeErrorFormat(e.Error())
			if err != nil || !strings.HasPrefix(result.Detail, "data: true") {
				loggerHook.Errorw("send", "type", t, "err", e)
			} else {
				loggerHook.Infow("send", "type", t, "result", result.Detail)
			}
		} else {
			loggerHook.Infow("send", "type", t, "resp", resp)
		}
	}
}
